package com.elmcode.server.utils;

import com.elmcode.server.exception.TokenException;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JWTUtil {

    public static void main(String[] args) throws Exception {

        Map<String,Object> payloadInfo = new HashMap<>();
        payloadInfo.put("name","laozj");
        payloadInfo.put("address","guangxi");


        String token = generateToken(payloadInfo,"123456",24*60*60);

        System.out.println("生成的token："+token);
//
//        token=token+"1";
//
        payloadInfo =  parseJWT(token,"123456");
        System.out.println("解析之后得到的数据：");
        System.out.println("name："+payloadInfo.get("name"));
        System.out.println("address："+payloadInfo.get("address"));

    }

    public static final String USER_ID = "user_id";

    public static final String CUSTOMER_ID = "customer_id";

    /**
     *  //对称加密
     * 生成token
     * @param claimInfo 封装到token里面的数据
     * @param key  自定义key
     * @param expire  过期时间
     * @return token字符串
     */
    public static String generateToken(Map<String,Object> claimInfo, String key, int expire)  {

        long expMillis = System.currentTimeMillis() + expire*1000;
        Date exp = new Date(expMillis);

        return Jwts.builder()
                .setClaims(claimInfo)
                .setExpiration(exp)
                .signWith(SignatureAlgorithm.HS256,key)
                .compact();
    }

    /**
     * 从token中获取原始信息
     * @param token  一个字符串
     * @param key  与token相匹配的key（密码）
     * @return
     * @throws Exception
     */
    public static Map<String,Object> parseJWT(String token, String key) throws Exception {
        Claims body = null;
        try {
            Jws<Claims> claimsJws = Jwts.parser().setSigningKey(key).parseClaimsJws(token);
            body = claimsJws.getBody();
        }catch (Exception e){
            throw new TokenException();
        }
        return body;
    }
}